package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//  自定义未授权访问处理类
@Slf4j
@Service
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    // 当访问受保护的资源时,如果用户未被授权,此方法被调用
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.debug("未授权访问");
        // 设置Http响应码为未授权(状态码 401)
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 设置响应类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        //  获取响应的PrintWriter对象,用于写入响应内容
        PrintWriter writer =response.getWriter();
        //构造表示未登录的JSON结果对象
        JsonResult result = new JsonResult(StatusCode.NOT_LOGIN);
        // 将JSON结果对象转为JSON字符串写入响应
        writer.write(JSON.toJSONString(result));
        //  刷新输出流
        writer.flush();
        //  关闭输出流
        writer.close();
    }
}
